#!/usr/bin/env node
const chalk = require("chalk");
const inquirer = require("inquirer");
const downgit = require("download-git-repo");
const ora = require("ora");
const handlebars = require("handlebars");
const fs = require("fs");
const path = require("path");

// 命令
const commander = require("commander");
commander.command("create").action(() => {
  console.log(chalk.rgb(85, 88, 217)(`欢迎使用jtljia脚手架构建工具`));
  inquirer
    .prompt([
      {
        type: "input",
        name: "projectName",
        message: "请输入项目名称",
        validate: (input) => {
          input = String(input ?? "").trim();
          if (!input) {
            return "项目名称不能为空";
          }
          return true;
        },
      },
      {
        type: "list",
        name: "type",
        message: "请选择需要创建的项目框架",
        choices: ["vue3"],
      },
    ])
    .then((answers) => {
      let { projectName, type } = answers;
      projectName = String(projectName).trim();
      switch (type) {
        case "vue3":
          createVue(projectName);
          break;
      }
    });
});

/**
 * @desc 创建vue项目
 */
function createVue(projectName) {
  inquirer
    .prompt([
      {
        type: "list",
        name: "type",
        message: "请选择需要创建的项目依赖",
        choices: [
          "vue3 + elementPlus",
          "vue3 + elementPlus + tailwind",
          "vue3 + elementPlus + tailwind + jtljia-ui",
        ],
      },
    ])
    .then((answers) => {
      projectName = String(projectName).trim();
      const targetPath = path.join(process.cwd(), projectName);
      let { type } = answers;
      switch (type) {
        case "vue3 + elementPlus":
          downVue3({
            path: "https://gitee.com:cellllllllll/micro-base-v3-webpack#master",
            targetPath,
            projectName,
          });
          break;
        case "vue3 + elementPlus + tailwind":
          downVue3({
            path: "https://gitee.com:cellllllllll/micro-base-v3-webpack#tailwind",
            targetPath,
            projectName,
          });
          break;
        case "vue3 + elementPlus + tailwind + jtljia-ui":
          downVue3({
            path: "https://gitee.com:cellllllllll/micro-base-v3-webpack#tailwind+jtljia-ui",
            targetPath,
            projectName,
          });
          break;
      }
    });
}

function downVue3({ path, targetPath, projectName }) {
  const downFn = () => {
    const spinner = ora("下载中").start();
    downgit(path, projectName, { clone: true }, function (err) {
      spinner.stop();
      if (err) {
        console.log(chalk.red("模板下载失败!"));
      } else {
        const packagePath = `${projectName}/package.json`;
        const packageContent = fs.readFileSync(packagePath, "utf8");
        const packageResult = handlebars.compile(packageContent)({
          name: projectName,
        });
        fs.writeFileSync(packagePath, packageResult);
        const success = chalk.hex("#FFA500");
        console.log(success("模板初始化成功！"));
        console.log(success(`\ncd ${projectName}`));
        console.log(success(`npm i`));
        console.log(success(`npm run dev`));
      }
    });
  };
  if (fs.existsSync(targetPath)) {
    inquirer
      .prompt({
        type: "confirm",
        name: "exist",
        message: "目录已存在，是否覆盖？",
      })
      .then(({ exist }) => {
        if (exist) {
          fs.rm(
            targetPath,
            {
              recursive: true,
            },
            function (err) {
              if (err) {
                console.log(err);
                console.log(chalk.red("目录删除失败!"));
              } else {
                downFn();
              }
            }
          );
        } else {
          process.exit(1);
        }
      });
  } else {
    downFn();
  }
}
// 定义版本
commander.version("1.1.0");
// 绑定解析
commander.parse(process.argv);
